<?php

/**
 * 将view使用的js和css分开处理，css放在header输出，js放在body结束前输出
 *
 * @author Perry
 **/
Class SgwyHelper extends AppHelper{

    public $helpers = array('Html');

    private $cssFiles = array();
    private $jsFiles = array();

    private $compressJsFiles = array();
    private $compressCssFiles = array();

    /**
     * 增加css文件到最前面
     *
     * @author Perry
     **/
    public function prependCss($cssFiles, $compress = false){
        if(empty($cssFiles)){
            return;
        }
        if(!is_array($cssFiles)){
            $cssFiles = (array) $cssFiles;
        }
        foreach($cssFiles as $index => $file){
            $file = $cssFiles[$index] = trim($file);
            if(in_array($file, $this->cssFiles)){
                unset($cssFiles[$index]);
            }
        }
        if(!empty($cssFiles)){
            $this->cssFiles = array_merge($cssFiles, $this->cssFiles);
            if($compress){
                $this->compressCssFiles = array_merge($cssFiles, $this->compressCssFiles);
            }
        }
    }

    /**
     * 增加js文件到最前面
     *
     * @author Perry
     **/
    public function prependJs($jsFiles, $compress = false){
        if(empty($jsFiles)){
            return;
        }
        if(!is_array($jsFiles)){
            $jsFiles = (array) $jsFiles;
        }
        foreach($jsFiles as $index => $file){
            $file = $jsFiles[$index] = trim($file);
            if(in_array($file, $this->jsFiles)){
                unset($jsFiles[$index]);
            }
        }
        if(!empty($jsFiles)){
            $this->jsFiles = array_merge($jsFiles, $this->jsFiles);
            if($compress){
                $this->compressJsFiles = array_merge($jsFiles, $this->compressJsFiles);
            }
        }
    }

    /**
     * 增加css文件
     *
     * @author Perry
     */
    function addCss($css, $compress = false){
        $css = trim($css);
        if($css && !in_array($css, $this->cssFiles)){
            $this->cssFiles[] = $css;
            if($compress){
                $this->compressCssFiles[] = $css;
            }
        }
    }

    /**
     * 增加js文件
     *
     * @author Perry
     */
    function addJs($js, $compress = false){
        $js = trim($js);
        if($js && !in_array($js, $this->jsFiles)){
            $this->jsFiles[] = $js;
            if($compress){
                $this->compressJsFiles[] = $js;
            }
        }
    }

    /**
     * 获取css文件
     *
     * @author Perry
     **/
    function getCssFiles() {
        return $this->cssFiles;
    }

    /**
     * 获取js文件
     *
     * @author Perry
     **/
    function getJsFiles() {
        return $this->jsFiles;
    }

    
    /**
     * 将email部分字符转换成 *
     *
     * @author shensuoming
     **/
    function maskEmail($email) {
        if (strpos ( $email, '@' ) > 4) {
            $dot = "";
            for($i = 0; $i < strpos ( $email, '@' ) - 4; $i ++) {
                $dot .= "*";
            }
            return substr ( $email, 0, 3 ) . $dot . substr ( $email, strpos ( $email, '@' ) - 1 );
        } else if (strpos ( $email, '@' ) == 1) {
            return substr ( $email, 0, 0 ) . '*' . substr ( $email, strpos ( $email, '@' ) );
        } else if (strpos ( $email, '@' ) == 2) {
            return substr ( $email, 0, 1 ) . '*' . substr ( $email, strpos ( $email, '@' ) );
        } else if (strpos ( $email, '@' ) == 3) {
            return substr ( $email, 0, 1 ) . '*' . substr ( $email, strpos ( $email, '@' ) - 1 );
        } else if (strpos ( $email, '@' ) == 4) {
            return substr ( $email, 0, 2 ) . '*' . substr ( $email, strpos ( $email, '@')-1);
       }
    }

    /**
     * 返回包含js文件的script标签
     * 如果Cdn.combineAssets = true，则将所有站内js文件拼成一个script标签，使用assets.php输出
     * 如果Cdn.enable = true，则使用cdn上的assets.php
     * 所有站外文件使用单独的script标签
     * 
     * @author Perry
     **/
    public function getCombinedJsLink($combineAssets = true){
        if(empty($this->jsFiles)){
            return null;
        }
        $inSites = array();
        $outSites = array();
        $combineAssets = $combineAssets && Configure::read('combo_minify');
        foreach($this->jsFiles as $file){
            if(strpos($file, '://') === false && strpos($file, '//') !== 0){
                //站内js
                if($combineAssets){
                    //合并js，无需包含cdn域名
                    $url = $this->assetUrl($file, array(
                        'noCdn' => true,
                        'pathPrefix' => JS_URL, 
                        'ext' => '.js'));
                    if(in_array($file, $this->compressJsFiles)){
                        $url .= 'c';
                    }
                    $inSites[] = $url;
                }else{
                    //不合并js，直接输出script标签
                    $inSites[] = $this->Html->script($file);
                }
            }else{
                $outSites[] = $this->Html->script($file);
            }
        }
        if($combineAssets){
            //将所有js拼起来当作assets.php的参数
            $version = '258';
            $inSitePath = $this->assetUrl('/combo/minify.php?js=' . urlencode(implode('&', $inSites)).'&version='.$version);
            $inSiteScripts = sprintf('<script type="text/javascript" src="%s"></script>', $inSitePath);
        }else{
            $inSiteScripts = implode(' ', $inSites);
        }
        $outSiteScripts = implode(' ', $outSites);
        return $inSiteScripts . $outSiteScripts;
    }

    public function getCombinedCssLink($combineAssets=true){
        if(empty($this->cssFiles)){
            return null;
        }
        $inSites = array();
        $outSites = array();
        $combineAssets = $combineAssets && Configure::read('combo_minify');
        foreach($this->cssFiles as $file){
            if(strpos($file, '://') === false && strpos($file, '//') !== 0){
                //站内css
                if($combineAssets){
                    //合并css，无需包含cdn域名
                    $url = $this->assetUrl($file, array(
                        'noCdn' => true,
                        'pathPrefix' => CSS_URL, 
                        'ext' => '.css'));
                    if(in_array($file, $this->compressCssFiles)){
                        $url .= 'c';
                    }
                    $inSites[] = $url;
                }else{
                    //不合并css，直接输出css标签
                    $inSites[] = $this->Html->css($file);
                }
            }else{
                $outSites[] = $this->Html->css($file);
            }
        }
        if($combineAssets){
            //将所有css拼起来当作assets.php的参数
            $version = '258';
            $inSitePath = $this->assetUrl('/combo/minify.php?css=' . urlencode(implode('&', $inSites)).'&version='.$version);
            $inSiteStyles = sprintf('<link rel="stylesheet" type="text/css" href="%s" />', $inSitePath);
        }else{
            $inSiteStyles = implode(' ', $inSites);
        }
        $outSiteStyles = implode(' ', $outSites);
        return $inSiteStyles . $outSiteStyles;
    }

    function alert($error){
        if(empty($error)) return false;
        return '<div class="col-md-12" style="position: absolute;"></div>
                <div class="col-md-12 alert alert-danger" role="alert">'.$error.'</div>';
    }

    /**
     * 模态窗口
     */
    function alert_modal($title, $msg){
        echo '<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">'.$title.'</h4>
              </div>
              <div class="modal-body">
                '.$msg.'
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary">确认</button>
              </div>
            </div>
          </div>
        </div>';
    }

    function page_count($action){
        $ip = $this->get_real_ip();
        App::uses('RedisServer', 'Lib');
        RedisServer::init();
        RedisServer::$redis;
        $field = $ip.'-'.$action;
        $num = RedisServer::$redis->hget(RedisServer::REDIS_KEY_PAGE_COUNT, $field);
        if(is_numeric($num)){
            $num += 1;
        }else{
            $num = 0;
        }
        return RedisServer::$redis->hset(RedisServer::REDIS_KEY_PAGE_COUNT, $field, $num);
    }

    function get_real_ip(){
        $ip=false;  
        if(!empty($_SERVER["HTTP_CLIENT_IP"])){  
            $ip = $_SERVER["HTTP_CLIENT_IP"];  
        }  
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {  
            $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);  
            if ($ip) {
                array_unshift($ips, $ip); $ip = FALSE;
            }
            for ($i = 0; $i < count($ips); $i++) {  
                if (!eregi ("^(10|172\.16|192\.168)\.", $ips[$i])) {  
                    $ip = $ips[$i];  
                    break;  
                }  
            }  
        }  
        return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
    }

    /* 组合渠道url */
    function url_source($url){
        $params = $this->request->query;
        if(!empty($params['ref'])){
            $urls = explode('?', $url);
            if(count($urls) > 1){ // ?后面有参数
                $p = explode('&', $urls[1]);
                if(count($p) > 0 && !empty($urls[1])){ // 有多个参数 &
                    $urls[1].='&ref='.$params['ref'];
                }else{ // 没有参数 &
                    $urls[1].='ref='.$params['ref'];
                }
                return $urls[0].'?'.$urls[1];
            }else{
                return $urls[0].='?ref='.$params['ref'];
            }
        }
        return $url;
    }   

    function source_params($domain){
        $maps = array(
            'local.www.ivf51.com' => 'ref=51',
            'local.www.ivf56.com' => 'ref=56',
            'wx.ivf56.com' => 'ref=wx',
            'wb.ivf56.com' => 'ref=wb',
            'qq.ivf56.com' => 'ref=qq',
            'e.ivf56.com' => 'ref=e',
        );
        return isset($maps[$domain]) ? $maps[$domain] : '';
    }
}
